﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Irony.Parsing;

namespace ConciseMarkupLanguage.Terminals
{
    class FreeText : Terminal
    {
        public FreeText(string name)
            : base(name)
        {
        }

        private static bool IsEscaped(string str, int pos)
        {
            bool escaped = false;
            while (pos > 0 && str[--pos] == '\\') escaped = !escaped;
            return escaped;
        }

        public override Token TryMatch(ParsingContext context, ISourceStream source)
        {
            char? quote = null;

            while (!source.EOF())
            {
                if (source.NextPreviewChar == '"' || source.NextPreviewChar == '\'')
                {
                    if (quote.HasValue)
                    {
                        if (quote.Value == source.NextPreviewChar && !IsEscaped(source.Text, source.Text.Length))
                        {
                            quote = null;
                        }
                    }
                    else
                    {
                        quote = source.PreviewChar;
                    }
                }
                else if (source.NextPreviewChar == ')' && !quote.HasValue)
                {
                    break;
                }

                source.PreviewPosition++;
            }

            return source.CreateToken(OutputTerminal);
        }
    }
}
